import re
from django_redis import get_redis_connection
from rest_framework import serializers
from .models import User, Address
from rest_framework_jwt.settings import api_settings
from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU
from . import constants


class CreateUserSerializer(serializers.ModelSerializer):
    """注册序列化器"""
    #序列化器的所有字段['id','mobile','username','password','password2','sms_code','allow']
    #需要校验的字段 ['username', 'password', 'password2', 'mobile','sms-code', 'allow']
    #模型中已存在的字段['username', 'password','mobile']
    #需要序列化的字段 ['id', 'username', 'mobile']
    #需要反序列化的字段['username', 'password', 'password2', 'mobile','sms_code','allow']

    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='token', read_only=True)

    class Meta:
        model = User #从User模型中映射序列化器字段
        fields = ['id', 'mobile', 'username', 'password', 'password2', 'sms_code', 'allow', 'token'] #前端传过来的字段['id','mobile','username','password','password2','sms_code','allow']
        extra_kwargs = {#修改字段选项
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }
    def validate_mobile(self,value):
        """单独校验手机号"""
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式有误')
        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')

    def validate(self, attrs):
        """检验两个密码是否相同; attrs是前端传来的字典"""
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('请同意用户协议')


        #校验验证码
        redis_conn = get_redis_connection('verify_codes')#连接verify_code数据库
        mobile = attrs['mobile']#取出前端传过来的手机号
        real_sms_code = redis_conn.get('sms_%s' %mobile) #从redis数据库中取出验证码

        #向redis存储数据时都是以字符串进行存储的，取出来后都是bytes类型[bytes]
        if real_sms_code is None or attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('验证码错误')

        return attrs

    #password2,sms_code,allow不需要存储,所以要从attrs字典里面删除掉
    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        password = validated_data.pop('password') #先把password从字典中删除，并且赋值给password
        user = User(**validated_data) #给模型对象User赋值
        user.set_password(password) #把密码加密后再赋值给user模型对象的password
        user.save()#存储到数据库

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER #引用jwt中的夹袄jwt_payload_handler函数（生成payload)
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER #函数引用 生成jwt

        payload = jwt_payload_handler(user) #根据user生成用户相关的数据
        token = jwt_encode_handler(payload) #传入载荷生成完整的jwt
        user.token = token
        return user

class UserDetailSerializer(serializers.ModelSerializer):
    """用户详情序列化"""
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active'] #参考基本信息

class EmailSerializer(serializers.ModelSerializer):
    """更新邮箱序列化器"""
    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }
    def update(self, instance, validated_data):
        """重写此方法目录不是为了修改，而是借用此时机，发激活邮箱"""
        instance.email = validated_data.get('email')
        instance.save()
        #生成验证链接
        verify_url = instance.generate_email_verify_url()
        #发送验证邮件
        send_verify_email.delay(instance.email, verify_url)
        return instance

class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    没有直接映射model
    自定义province,city,district,province_id,city_id,district_id
    province,city,district只能做序列化
    province_id,city_id,district_id必填项
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        # 在序列化器中取到user并把它添加到反序列化之后的字典中
        validated_data['user'] = self.context['request'].user
        # 创建并保存地址中间就为了  地址关联用户
        address = Address.objects.create(**validated_data)

        return address

class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)

class AddUserBrowsingHistorySerializer(serializers.Serializer):
    """
    添加用户浏览历史序列化器
    """
    sku_id = serializers.IntegerField(label="商品SKU编号", min_value=1)

    def validate_sku_id(self, value):
        """
        检验sku_id是否存在
        """
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return value

    def create(self, validated_data):
        """
        保存
        """
        user_id = self.context['request'].user.id
        sku_id = validated_data['sku_id']
        #创建redis链接对象
        redis_conn = get_redis_connection("history")
        pl = redis_conn.pipeline()

        # 移除已经存在的本商品浏览记录;去重
        pl.lrem("history_%s" % user_id, 0, sku_id)
        # 添加新的浏览记录
        pl.lpush("history_%s" % user_id, sku_id)
        # 只保存最多5条记录
        pl.ltrim("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT-1)

        pl.execute()

        return validated_data

class SKUSerializer(serializers.ModelSerializer):
    """sku商品序列化器"""
    class Meta:
        model = SKU
        fields = ['id', 'name', 'price', 'default_image_url', 'comments']